/* eslint-disable max-lines */
import TauSimpleSelect from '@/components/TauSimpleSelect';
import { ellipsisRender } from '@/components/TauTable';
import * as BASE from '@/stores/definitions-base';
import { DatePicker, Input, Rating, Switch } from '@alifd/next';
import { t } from '@lingui/macro';
import React from 'react';

const {
  DATETIME_TEXT,
  DATETIMES_TEXT,
  DATE_TEXT,
  TIME_TEXT,
  EMPTY_TEXT,
  ENUMS: ENUMSBase,
  FieldsGrid: FieldGridBase,
  TitleGrid,
  column: columnBase,
  toSelectDataSource,
} = BASE;
export { DATETIMES_TEXT, DATETIME_TEXT, DATE_TEXT, EMPTY_TEXT, TIME_TEXT, TitleGrid, toSelectDataSource };

/**
 * @param {*} path        属性path
 * @param {*} props       column属性
 * @returns column定义
 */
export function column(...args) {
  return columnBase(model, ...args);
}

/**
 * 显示一组表单字段
 * ```js
 * {
 *   fields: string[],    // 字段名称，可以使用.来指定嵌套对象属性，例如order.busOrder.shift
 *   columns: number,     // 列数，默认为4,最大为12,最小为1
 *   model: object,       // 字段定义数据模型的根对象，默认不指定，仅在使用子对象作为根模型时设置
 *   overrideModel: object, // 重载字段定义数据模型
 *   mode: string,        // 表单模式，默认为edit，可选view
 *   itemLayout: object,  // FormItem布局配置，默认为{}
 * }
 * ```
 *
 * @param {object} param0
 * @returns
 */
export function FieldsGrid(props) {
  return <FieldGridBase model={model} {...props} />;
}

//----------------------------------------------------------------------
export const ENUMS = {
  ...ENUMSBase,
  // 0-已取消 1-发布中 2-已接单 3-已上客 4-已下客
  orderStatus: {
    '-1': t`已失效`,
    0: t`已取消`,
    1: t`已发布`,
    2: t`已接单`,
    3: t`已上客`,
    4: t`待打单`,
    5: t`已完成`,
  },
  status: {
    '-1': t`已退回`,
    0: t`已取消`,
    1: t`已接单`,
    2: t`已上客`,
    3: t`已下客待打单`,
    4: t`已完成`,
  },
  isRoundTrip: {
    true: t`往返`,
    false: t`单程`,
  },
  priceType: {
    0: t`普通线路`,
    1: t`澳门线路`,
  },
};

/**
 * 模型定义：
 * 1. 普通文本仅需要定义label
 * 2. 需要通过枚举转换的值，定义text; 当使用renderer返回组件时，text属性无效，需要通过组件的renderPreview来指定预览时的绘制方式
 * 3. 通用的ui属性需要定制时，定义ui; 特定模式(view, edit, add)下的ui，添加后缀定义为ui_<mode>，例如：ui_view, ui_edit, ui_add, ui_table
 * 4. ui可配置属性包括:
 *    renderer: 内容渲染函数, Form表单中的原型为：(value: any, formData: any, fieldDefinition: any) => ReactNode; Table Column中的原型为: (value: any, columnIndex: number, rowData: any) => ReactNode;
 *    itemProps: 表单Form.Item的属性，可以是对象，或函数({ isPreview: boolean, mode: string, value: any, formData: any, ...otherDefinitions}) => void;
 *    span: Grid Cell占用的列数, 默认为1
 *
 * 【注】获取接口的model定义后，vscode中通过正则替换：^(\s+)"label": "([^']+)"  ===> $1label: t`$2`
 */
export const model = {
  orderNumber: {
    label: t`订单编号`,
    ui: {
      renderer: (v) => <>{v}</>,
    },
  },
  changeBatch: {
    label: t`订单改签批次`,
  },
  changeAssociatedOrderIds: {
    label: t`改签关联订单id集合`,
  },
  discountInfos: {
    label: t`折扣信息`,
    type: {
      label: t`折扣类型 activity-活动 coupon-优惠券`,
    },
    activityId: {
      label: t`活动编号`,
    },
    activityName: {
      label: t`活动名称`,
    },
    couponId: {
      label: t`优惠券id`,
    },
    couponName: {
      label: t`优惠券名称`,
    },
    source: {
      label: t`优惠券来源<br/> DOUYIN 抖音<br/> PLATFORM 平台`,
    },
    sourceName: {
      label: t`优惠券来源名称`,
    },
    cost: {
      label: t`优惠券成本`,
    },
    discountPrice: {
      label: t`折扣价格`,
    },
    refundPrice: {
      label: t`退款金额`,
    },
    failure: {
      label: t`该优惠是否失效`,
    },
  },
  merchant: {
    label: t`关联商户`,
  },
  merchantPrice: {
    label: t`商户价格`,
  },
  merchantRootPrice: {
    label: t`商户基础价`,
  },
  merchantProfitSharing: {
    label: t`渠道对商户的分润`,
  },
  taskIds: {
    label: t`任务关联id`,
  },
  completionTime: {
    label: t`完成时间`,
  },
  orderChangeRemarks: {
    label: t`订单变更备注`,
  },
  username: {
    label: t`操作人账号`,
  },
  auxOrder: {
    label: t`司机群辅助订单`,
    publisherId: {
      label: t`发布人id`,
    },
    updatePointFlag: {
      label: t`是否手动更改积分`,
    },
    adjustmentPrice: {
      label: t`打单价格`,
      ui: {
        renderer: (v, r) => {
          const { price } = r;
          const totalPrice = Number(v) + Number(price);
          return <>{totalPrice?.toFixed(2)}</>;
        },
      },
    },
    priceType: {
      label: t`线路类型`,
      text: (v) => <>{ENUMS.priceType[v]}</>,
      ui_edit: {
        renderer: (v) => (
          <TauSimpleSelect
            value={v}
            data={toSelectDataSource(ENUMS.priceType)}
          />
        ),
      },
    },
    eightSeaterFlag: {
      label: t`是否八座车`,
      ui_edit: {
        renderer: (v) => (
          <Switch
            checked={v}
            checkedChildren={t`是`}
            unCheckedChildren={t`否`}
            autoWidth
            size="small"
          />
        ),
      },
    },
    scoreFlag: {
      label: t`是否记分`,
      ui_edit: {
        renderer: (v) => (
          <Switch
            checked={v}
            checkedChildren={t`是`}
            unCheckedChildren={t`否`}
            autoWidth
            size="small"
          />
        ),
      },
    },
    isRoundTrip: {
      label: t`是否往返`,
      text: (v) => <>{v ? t`是` : t`否`}</>,
      ui_edit: {
        renderer: (v) => (
          <Switch
            checked={v}
            checkedChildren={t`是`}
            unCheckedChildren={t`否`}
            autoWidth
            size="small"
          />
        ),
      },
    },
    publisherName: {
      label: t`出单人群编号 / 昵称`,
      text: (v, r) => <>{r?.publisherMemberId} / {v}</>,
      ui: {
        renderer: (v, r) => {
          const { publisherMemberId } = r;
          return <>{`${publisherMemberId}【${v}】`}</>;
        },
      },
    },
    publisherPhone: {
      label: t`出单人联系方式`,
      ui: {
        renderer: (v, r) => {
          const { publisherWxAccount } = r;
          return <>{`${v}【${publisherWxAccount}】`}</>;
        },
      },
    },
    takeName: {
      label: t`接单人群编号/ 接单人 / 初始积分`,
      ui: {
        renderer: (v, r) => {
          const {
            takeOrderMemberId,
          } = r;
          const {
            driverName,
            point = t`无`,
          } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
          return (
            <>
              <span>{driverName ? `${takeOrderMemberId} ${driverName}【${r?.takeOrderName || t`无`}】` : t`无`}</span>
              <span>{`/ ${point}`}</span>
            </>
          );
        },
      },
    },
    takePhone: {
      label: t`接单人联系方式`,
      ui: {
        renderer: (v, r) => {
          const { driverPhone } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
          return <>{driverPhone ? `${driverPhone}【${r?.takeOrderWxAccount || t`无`}】` : t`无`}</>;
        },
      },
    },
    publisherGroup: {
      label: t`发布人姓名/号码`,
      text: (v, r) => {
        const { publisherName, publisherPhone } = r?.auxOrder;
        return <>{`${publisherName || '无'}/${publisherPhone || '无'}`}</>;
      },
    },
    groupId: {
      label: t`群id`,
    },
    groupName: {
      label: t`群名称`,
      ui: {
        renderer: (v) => <>{v}</>,
      },
    },
    issueOrderPoint: {
      label: t`出单计分`,
      ui: {
        renderer: (v) => <>{v}</>,
      },
    },
    takeOrderPoint: {
      label: t`接单计分`,
      ui: {
        renderer: (v) => <>{v}</>,
      },
    },
    takeOrderGroup: {
      label: t`发/接单积分`,
      text: (v, r) => {
        const { issueOrderPoint, takeOrderPoint } = r?.auxOrder;
        return <>{`${issueOrderPoint}/${takeOrderPoint}`}</>;
      },
    },
    orderStatus: {
      label: t`订单状态`,
      text: (v) => <>{ENUMS.orderStatus[v]}</>,
      ui: {
        renderer: (v) => <>{ENUMS.orderStatus[v]}</>,
      },
    },
    predictBeginDate: {
      label: t`行程开始时间`,
      text: DATETIME_TEXT,
      ui_edit: {
        renderer: (v) => (
          <DatePicker
            value={DATETIME_TEXT(v)}
            style={{ width: '100%' }}
            showTime
          />),
      },
    },
    takeOrderTime: {
      label: t`接单时间`,
      text: DATETIME_TEXT,
      ui: {
        renderer: (v, r) => {
          const { takeOrderTime } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
          return <>{takeOrderTime ? DATETIME_TEXT(takeOrderTime) : t`无`}</>;
        },
      },
    },
    content: {
      label: t`发布内容`,
      text: (v) => <>{ellipsisRender(v)}</>,
      ui: {
        renderer: (v) => <>{v}</>,
        span: 4,
      },
    },
    remarks: {
      label: t`备注`,
      ui: {
        renderer: (v) => <Input.TextArea value={v || '无'} />,
        span: 4,
      },
    },
    auxTask: {
      label: t`辅助任务`,
      id: {
        label: t`辅助任务id`,
      },
      driverInfos: {
        label: t`接单司机信息`,
        driverId: {
          label: t`接单司机id`,
        },
        driverName: {
          label: t`接单人群编号 / 昵称 / 初始积分`,
          text: (v, r) => {
            const { driverName, point = t`无` } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
            return (
              <>
                <span>{`${r?.takeOrderMemberId} / ${driverName || t`无`}`}</span>
                <span>{`/ ${point}`}</span>
              </>
            );
          },
          ui: {
            renderer: (v, r) => {
              const { driverName } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
              return <>{driverName || t`无`}</>;
            },
          },
        },
        driverPhone: {
          label: t`接单司机号码`,
          ui: {
            renderer: (v, r) => {
              const { driverPhone } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
              return <>{driverPhone || t`无`}</>;
            },
          },
        },
        driverGroup: {
          label: t`接单司机名字/号码`,
          text: (v, r) => {
            const { driverName, driverPhone } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
            return (
              <>
                {driverName ? (
                  <>
                    <div>{driverName}</div>
                    <div>{driverPhone}</div>
                  </>
                ) : <div>{t`无`}</div>}
              </>);
          },
        },
        takeOrderTime: {
          label: t`接单时间`,
          text: (v, r) => {
            const { takeOrderTime } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
            return <>{takeOrderTime ? DATETIME_TEXT(takeOrderTime) : t`无`}</>;
          },
        },
        status: {
          label: t`司机状态`,
          text: (v, r) => {
            const { status } = rootStore.orderStore._table_driver(r?.auxOrder?.auxTask?.driverInfos) || {};
            return <>{ENUMS.status[status] || t`无`}</>;
          },
        },
      },
      feedbackInfo: {
        label: t`反馈信息`,
        content: {
          label: t`司机的下客反馈`,
          ui: {
            span: 2,
          },
        },
        star: {
          label: t`出单人的服务评价`,
          ui: {
            renderer: (v) => <Rating value={v} disabled isPreview />,
            span: 2,
          },
        },
        evaluateContent: {
          label: t`评价内容`,
          ui: {
            span: 2,
          },
        },
        attachments: {
          label: t`附件`,
          title: {
            label: t`反馈标题`,
          },
          description: {
            label: t`反馈说明`,
          },
          binaryId: [{
            label: t`附件id`,
          }],
        },
      },
      dispatchInformation: {
        label: t`派车信息`,
        carId: {
          label: t`车辆id`,
        },
        hkLicense: {
          label: t`香港车牌号`,
        },
        mainlandLicense: {
          label: t`大陆车牌号`,
        },
        licenseGroup: {
          label: t`车牌号码(大陆/香港)`,
          ui: {
            renderer: (v, r) => {
              const { mainlandLicense = t`无`, hkLicense = t`无` } = r?.auxOrder?.auxTask?.dispatchInformation || {};
              return <>{`${mainlandLicense} / ${hkLicense}`}</>;
            },
          },
        },
        dispatchTime: {
          label: t`派车时间`,
          text: DATETIME_TEXT,
          ui: {
            renderer: (v) => DATETIME_TEXT(v) || t`无`,
          },
        },
        driverId: {
          label: t`司机id`,
        },
        name: {
          label: t`服务司机`,
        },
        wxAccount: {
          label: t`司机微信号`,
        },
        mainPhone: {
          label: t`大陆手机号`,
        },
        hkPhone: {
          label: t`香港手机号`,
        },
        contactInformation: {
          label: t`司机联系方式`,
          ui: {
            renderer: (v, r) => {
              const { wxAccount, mainPhone } = r?.auxOrder?.auxTask?.dispatchInformation || {};
              let text = mainPhone;
              if (wxAccount) {
                text += `【${wxAccount}】`;
              }
              return <>{text}</>;
            },
          },
        },
      },
    },
    consoleRemarks: {
      label: t`控制台备注`,
      ui: {
        renderer: (v) => <Input.TextArea value={v} />,
        span: 4,
      },
    },
    onArea: {
      label: t`上车区域`,
    },
    offArea: {
      label: t`下车区域`,
    },
  },
  transactionId: {
    label: t`微信支付订单号`,
  },
  prepayId: {
    label: t`微信预支付生成的标识<br/> 首次发起支付时生成，支付过程中断后再次支付时提供`,
  },
  price: {
    label: t`出单价格`,
    text: (v, r) => {
      const { auxOrder } = r;
      const totalPrice = auxOrder?.adjustmentPrice ? v + auxOrder?.adjustmentPrice : v;
      return <>{totalPrice ? totalPrice.toFixed(2) : totalPrice}</>;
    },
    ui_edit: {
      renderer: (v) => <Input value={v} />,
      itemProps: { required: true, format: 'number' },
    },
    ui_view: {
      renderer: (v) => <>{v?.toFixed(2)}</>,
    },
  },
  originalPrice: {
    label: t`原价`,
  },
  currency: {
    label: t`币种<br/> - RMB<br/> - HKD<br/> - MOP`,
  },
  orderType: {
    label: t`订单类型<br/> - 1 包车订单<br/> - 2 专线订单<br/> - 3 巴士订单<br/> - 4 拼车订单<br/> - 5 司机群辅助订单`,
  },
  relation: {
    label: t`关联订单<br/> 记录发起返空线路的原订单。不为空则表示为特惠订单。`,
  },
  notices: {
    label: t`通知控制信息<br/> 第二次将不发送通知`,
  },
  enableProfitShare: {
    label: t`是否开启分账`,
  },
  partnerProfitShare: {
    label: t`合伙人是否需要分账`,
  },
  accountRequestInfos: {
    label: t`分账请求信息列表`,
    appId: {
      label: t`appId`,
    },
    id: {
      label: t`订单id`,
    },
    transactionId: {
      label: t`微信支付订单号`,
    },
    outOrderNo: {
      label: t`商户系统内部的分账单号`,
    },
    orderId: {
      label: t`微信分账单号,微信支付系统返回的唯一标识`,
    },
    state: {
      label: t`分账单状态（每个接收方的分账结果请查看receivers中的result字段）<br/> 1、PROCESSING：处理中<br/> 2、FINISHED：分账完成`,
    },
    receivers: {
      label: t`分账方信息列表`,
      type: {
        label: t`分账接收方类型<br/> 1、MERCHANT_ID：商户号<br/> 2、PERSONAL_OPENID：个人openid（由父商户APPID转换得到）`,
      },
      description: {
        label: t`分账的原因描述，分账账单中需要体现`,
      },
      account: {
        label: t`分账接收方账号：<br/> 1、类型是MERCHANT_ID时，是商户号（mch_id或者sub_mch_id）<br/> 2、类型是PERSONAL_OPENID时，是个人openid`,
      },
      username: {
        label: t`合伙人 / 公司 / 司机`,
      },
      name: {
        label: t`合伙人名 / 公司名 / 司机`,
      },
      userType: {
        label: t`身份 1-合伙人 2-公司 3-司机`,
      },
      amount: {
        label: t`分账金额 单位为分，只能为整数，不能超过原订单支付金额及最大分账比例金额`,
      },
      result: {
        label: t`分账结果<br/> 1、PENDING：待分账<br/> 2、SUCCESS：分账成功<br/> 3、CLOSED：已关闭`,
      },
      failReason: {
        label: t`分账失败原因，当分账结果result为CLOSED（已关闭）时，返回该字段<br/> 1、ACCOUNT_ABNORMAL：分账接收账户异常<br/> 2、NO_RELATION：分账关系已解除<br/> 3、RECEIVER_HIGH_RISK：高风险接收方<br/> 4、RECEIVER_REAL_NAME_NOT_VERIFIED：接收方未实名<br/> 5、NO_AUTH：分账权限已解除<br/> 6、RECEIVER_RECEIPT_LIMIT：接收方已达收款限额<br/> 7、PAYER_ACCOUNT_ABNORMAL：分出方账户异常`,
      },
      detailId: {
        label: t`微信分账明细单号`,
      },
      inflowPlatform: {
        label: t`这笔资金是否放回平台`,
      },
      redistribute: {
        label: t`重新分账信息`,
        outOrderNo: {
          label: t`商户系统内部的分账单号`,
        },
        orderId: {
          label: t`微信分账单号,微信支付系统返回的唯一标识`,
        },
        state: {
          label: t`分账单状态（每个接收方的分账结果请查看receivers中的result字段）<br/> 1、PROCESSING：处理中<br/> 2、FINISHED：分账完成`,
        },
        result: {
          label: t`分账结果<br/> 1、PENDING：待分账<br/> 2、SUCCESS：分账成功<br/> 3、CLOSED：已关闭`,
        },
        failReason: {
          label: t`分账失败原因，当分账结果result为CLOSED（已关闭）时，返回该字段`,
        },
        detailId: {
          label: t`微信分账明细单号`,
        },
      },
    },
  },
  source: {
    label: t`订单来源`,
    targetType: {
      label: t`帐户类型<br/> 由调用方根据分账方身份类型定义，例如：COMPANY,PARTNER,CHANNEL等`,
    },
    targetId: {
      label: t`targetType下的帐户标识`,
    },
    targetName: {
      label: t`帐户名`,
    },
  },
  attribution: {
    label: t`订单归属`,
    targetType: {
      label: t`帐户类型<br/> 由调用方根据分账方身份类型定义，例如：COMPANY,PARTNER,CHANNEL等`,
    },
    targetId: {
      label: t`targetType下的帐户标识`,
    },
    targetName: {
      label: t`帐户名`,
    },
  },
  crBy: {
    label: t`创建者`,
  },
  upBy: {
    label: t`最后修改者`,
  },
  crDate: {
    label: t`出单时间`,
    text: DATETIME_TEXT,
    ui: {
      renderer: DATETIME_TEXT,
    },
  },
  upDate: {
    label: t`最后修收时间`,
  },
  tenantId: {
    label: t`租户ID`,
  },
  remark: {
    label: t`备注`,
    ui: {
      span: 4,
    },
  },
  publisherMemberId: {
    label: t`出单人成员群id`,
  },
  takeOrderMemberId: {
    label: t`接单人成员群id`,
  },

  // 前端新增
  keepScore: {
    label: t`计分`,
    text: (v, r) => {
      const { issueOrderPoint } = r?.auxOrder;
      return <>{issueOrderPoint}</>;
    },
  },
  itinerary: {
    label: t`行程`,
    text: (v, r) => {
      const { isRoundTrip, onArea, offArea } = r?.auxOrder;
      let text = (
        <>
          <div>{`${onArea}`}</div>
          <div>{`~ ${offArea}`}</div>
        </>
      );
      if (isRoundTrip) {
        text = (
          <>
            <div>{`(${ENUMS.isRoundTrip[isRoundTrip]}) ${onArea}`}</div>
            <div>{`~ ${offArea}`}</div>
          </>
        );
      }
      return <>{ellipsisRender(text)}</>;
    },
  },
};
